<?php
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
    header("Location: login.html");
    exit();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>刷步数小工具</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/style.css">
    <style>
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
            background: rgba(255,255,255,0.9);
        }
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            padding: 12px;
            font-weight: 600;
        }
        .form-control {
            border-radius: 10px;
            border: 1px solid #e0e0e0;
            padding: 12px;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
    </style>
</head>
<body style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh;">
    <?php include 'includes/navbar.php'; ?>
    
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card p-4 mb-4">
                    <h2 class="mb-4 text-center text-primary">小米运动刷步数小工具</h2>
                    <form id="updateStepsForm">
                        <div class="mb-3">
                            <label for="account" class="form-label">账号</label>
                            <input type="text" class="form-control" id="account" name="account" placeholder="请输入小米运动账号" required>
                        </div>
                        <div class="mb-3">
                            <label for="password" class="form-label">密码</label>
                            <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码" required>
                        </div>
                        <div class="mb-3">
                            <label for="steps" class="form-label">步数</label>
                            <input type="number" class="form-control" id="steps" name="steps" placeholder="请输入目标步数" min="1" max="99999" required>
                            <div class="form-text">建议步数范围：1000-99999</div>
                        </div>
                        <button type="submit" class="btn btn-primary w-100" id="submitBtn">
                            <span id="submitText">更新步数</span>
                            <div id="submitSpinner" class="spinner-border spinner-border-sm d-none" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </button>
                    </form>
                    <div id="result" class="mt-3"></div>
                </div>

                <div class="card p-4">
                    <h3 class="mb-4 text-center text-primary">使用说明</h3>
                    <ol class="list-group list-group-flush">
                        <li class="list-group-item d-flex align-items-center">
                            <span class="badge bg-primary me-2">1</span>
                            下载并安装 <strong>Zepp Life</strong> 应用（原小米运动）
                        </li>
                        <li class="list-group-item d-flex align-items-center">
                            <span class="badge bg-primary me-2">2</span>
                            使用手机号或邮箱注册账号
                        </li>
                        <li class="list-group-item d-flex align-items-center">
                            <span class="badge bg-primary me-2">3</span>
                            在应用中绑定微信、支付宝等第三方平台
                        </li>
                        <li class="list-group-item d-flex align-items-center">
                            <span class="badge bg-primary me-2">4</span>
                            在此处填写账号密码和步数进行同步
                        </li>
                    </ol>
                    <div class="alert alert-info mt-3">
                        <small>
                            <strong>注意：</strong> 
                            请确保使用小米运动（Zepp Life）官方账号，步数同步可能会有几分钟延迟。
                        </small>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.getElementById('updateStepsForm').addEventListener('submit', async function(event) {
            event.preventDefault();
            
            const account = document.getElementById('account').value.trim();
            const password = document.getElementById('password').value.trim();
            const steps = document.getElementById('steps').value.trim();
            const submitBtn = document.getElementById('submitBtn');
            const submitText = document.getElementById('submitText');
            const submitSpinner = document.getElementById('submitSpinner');
            const resultDiv = document.getElementById('result');

            // 验证输入
            if (!account || !password || !steps) {
                showResult('请填写所有必填字段', 'danger');
                return;
            }

            if (steps < 1 || steps > 99999) {
                showResult('步数必须在1-99999之间', 'danger');
                return;
            }

            // 显示加载状态
            submitBtn.disabled = true;
            submitText.textContent = '提交中...';
            submitSpinner.classList.remove('d-none');
            resultDiv.innerHTML = '';

            try {
                // 使用可用的API
                const response = await fetch(`https://api.5k4.cn/api/zeep?key=2e1ea3f60e06d0c5&account=${encodeURIComponent(account)}&password=${encodeURIComponent(password)}&steps=${encodeURIComponent(steps)}`, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json',
                    }
                });

                if (!response.ok) {
                    throw new Error(`网络错误: ${response.status}`);
                }

                const data = await response.json();
                
                if (data.code === 1 || data.code === '1') {
                    throw new Error(data.msg || data.message || '提交失败');
                }

                // 成功响应
                showResult(`步数更新成功！已设置 ${steps} 步`, 'success');
                
                // 清空表单
                document.getElementById('updateStepsForm').reset();

            } catch (error) {
                console.error('Error:', error);
                let errorMessage = '更新失败，请检查账号密码是否正确';
                
                if (error.message.includes('网络错误')) {
                    errorMessage = '网络连接失败，请检查网络连接';
                } else if (error.message.includes('账号') || error.message.includes('密码')) {
                    errorMessage = error.message;
                }
                
                showResult(errorMessage, 'danger');
            } finally {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitText.textContent = '更新步数';
                submitSpinner.classList.add('d-none');
            }
        });

        function showResult(message, type) {
            const resultDiv = document.getElementById('result');
            const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
            resultDiv.innerHTML = `<div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>`;
        }

        // 输入验证
        document.getElementById('steps').addEventListener('input', function() {
            if (this.value > 99999) {
                this.value = 99999;
            }
            if (this.value < 1) {
                this.value = 1;
            }
        });
    </script>
</body>
</html>